<?php

namespace wxshop;
use think\facade\Db;
class ShopSharer extends Common
{
    public static $AccessToken = '';
    public function __construct($appid,$secret){
        if($appid && $secret){
            $this->access_token = $this->getAccessToken($appid, $secret);
        }else{
            return false;
        }
    }

    public function getSharer1($store_id,$list=[],$page = 1){
        $url = 'https://api.weixin.qq.com/channels/ec/sharer/get_sharer_list?access_token='.$this->access_token;
        $postdata = ['sharer_type'=> 1,'page'=> $page,'page_size'=>100];
        $res = $this->post($url,json_encode($postdata,320));
        $res = json_decode($res,true);
        if($res['errcode'] == 0 && isset($res['sharer_info_list']) && $res['sharer_info_list']!=[]){
            $list = $list + $res['sharer_info_list'];
            $page += 1;
            return $this->getSharer1($store_id,$list,$page);
        }
        if($list){
            foreach ($list as $k=>$v){
                $list[$k]['store_store_id'] = $store_id;
                if(!Db::name('store_sharer')->where('sharer_type',1)->where('store_store_id',$store_id)->where('openid',$v['openid'])->find()){
                    Db::name('store_sharer')->insert($list[$k]);
                }
            }

        }

        return true;
    }

    public function getSharer0($store_id,$list=[],$page = 1){
        $url = 'https://api.weixin.qq.com/channels/ec/sharer/get_sharer_list?access_token='.$this->access_token;
        $postdata = ['sharer_type'=> 0,'page'=> $page,'page_size'=>100];
        $res = $this->post($url,json_encode($postdata,320));
        $res = json_decode($res,true);
        if($res['errcode'] == 0 && isset($res['sharer_info_list']) && $res['sharer_info_list']!=[]){
            $list = $list + $res['sharer_info_list'];
            $page += 1;
            return $this->getSharer0($store_id,$list,$page);
        }
        if($list){
            foreach ($list as $k=>$v){
                $list[$k]['store_store_id'] = $store_id;
                if(!Db::name('store_sharer')->where('sharer_type',0)->where('store_store_id',$store_id)->where('openid',$v['openid'])->find()){
                    Db::name('store_sharer')->insert($list[$k]);
                }
            }

        }

        return true;
    }

}